//
//  KunDataHelper.swift
//  KunLanCamera
//
//  Created by 李东 on 2024/3/23.
//

import UIKit
import HandyJSON
class KunDataHelper: NSObject {

    static let shared = KunDataHelper()
    let LocalKey = "dataKey"
    lazy var array = [KunRecordModel]()
    



    
    func getLocalList() -> [KunRecordModel] {
        if !array.isEmpty {
            return array
        }
        if let tt = UserDefaults.standard.object(forKey: LocalKey) as? String {
            if let list = [KunRecordModel].deserialize(from: tt) as? [KunRecordModel] {
                array = list
            }
        }
        return array
    }
    
    func addData(model: KunRecordModel)  {
        if array.contains(where: {$0.ts == model.ts}) {
            if let ii = array.firstIndex(where: {$0.ts == model.ts}) {
                array[ii] = model
            }
        }else {
//            array.append(model)
            array.insert(model, at: 0)
        }
        if let json = array.toJSONString() {
            UserDefaults.standard.set(json, forKey: LocalKey)
            UserDefaults.standard.synchronize()
        }
    }
}
